package com.ldy.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

public class SmsUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(SmsUtil.class);
	
	public static final CacheMap<String, String> cache = new CacheMap<>(5 * 60 * 1000);

	// 阿里云账号AccessKey ID和AccessKey Secret
	public static final String ACCESS_KEY_ID = "LTAI5tFi5DiyGezb2GxSr6ox";
	public static final String ACCESS_KEY_SECRET = "psC3ZbGnIqres3BrZDD9DAhfQX3XCk";

	// 短信服务所在区域ID，例如：cn-hangzhou
	public static final String REGION_ID = "cn-hangzhou";

	// 短信签名名称
	public static final String SIGN_NAME = "西藏小黑信息科技";

	// 短信模板CODE
	public static final String TEMPLATE_CODE = "SMS_305551451";

	// 接收短信的电话号码
	public static final String PHONE_NUMBER = "18701503529";

	// 模板参数，JSON格式字符串
	public static final String TEMPLATE_PARAM = "{\"code\":\"123456\"}";
	
	/**
	 * 发生验证码
	 * @param phone
	 * @param vcode
	 */
	public static boolean sendEcode(String phone, String vcode) {
		// 初始化DefaultProfile
		DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

		// 创建DefaultAcsClient实例
		IAcsClient client = new DefaultAcsClient(profile);

		// 创建SendSmsRequest对象
		SendSmsRequest request = new SendSmsRequest();
		request.setPhoneNumbers(phone);
		request.setSignName(SIGN_NAME);
		request.setTemplateCode(TEMPLATE_CODE);
		JSONObject param = new JSONObject();
		param.put("code", vcode);
		request.setTemplateParam(param.toJSONString());

		try {
			// 发送短信并获取响应
			SendSmsResponse response = client.getAcsResponse(request);
			logger.info("短信发送结果:{}", JSONObject.toJSONString(response));
			// 判断是否发送成功
			return "OK".equals(response.getCode());
			
		} catch (ClientException e) {
			logger.info("短信发送异常:{}",  e.getErrMsg());
			return false;
		}
	}

	public static void main(String[] args) {
		// 初始化DefaultProfile
		DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

		// 创建DefaultAcsClient实例
		IAcsClient client = new DefaultAcsClient(profile);

		// 创建SendSmsRequest对象
		SendSmsRequest request = new SendSmsRequest();
		request.setPhoneNumbers(PHONE_NUMBER);
		request.setSignName(SIGN_NAME);
		request.setTemplateCode(TEMPLATE_CODE);
		request.setTemplateParam(TEMPLATE_PARAM);

		try {
			// 发送短信并获取响应
			SendSmsResponse response = client.getAcsResponse(request);

			// 判断是否发送成功
			if ("OK".equals(response.getCode())) {
				System.out.println("短信发送成功！");
			} else {
				System.out.println("短信发送失败，错误信息：" + response.getMessage());
			}
		} catch (ClientException e) {
			e.printStackTrace();
			System.out.println("短信发送失败，异常信息：" + e.getErrMsg());
		}
	}
}